package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**发送短信验证码*/
    @PostMapping("/sendMsg")

    public R sendMsg(HttpSession session, @RequestBody Map<String, String> map) {
        //1. 获取手机号
        String phone = map.get("phone");
        //1.1 判断redis中是否存在这个key，如果存在：上次发送的key还未过期
        if (redisTemplate.hasKey(phone)) {
            throw new CustomException("上次发送的验证码还未过期，不允许重复发送");
        }
        //2. 随机生成验证码
//        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        String code = "123456";
        //3. 调用工具类发送短信验证码
        //SMSUtils.sendMessage("ABC商城", "SMS_205884038", phone, code);
        //4. 把验证码存入session key:phone  value:验证码
//        session.setAttribute(phone, code);
        //将数据存入缓存中,设置时间3分钟
        redisTemplate.opsForValue().set(phone,code,3, TimeUnit.MINUTES);
        return R.success("发送短信验证码成功");
    }

    /**
     * 用户登陆
     *
     */
    @PostMapping("/login")
    public R login(HttpSession session, @RequestBody Map<String, String> map) {
        //1. 获取用户输入手机号，验证码
        String phone = map.get("phone");
        String code = map.get("code");
        //2. 获取session中的验证码
//        Object codeInSession = session.getAttribute(phone);
        //2. 获取缓存中的验证码
        Object o = redisTemplate.opsForValue().get(phone);
        //3. 比对用户输入的验证码和session中的验证码
//        if (codeInSession == null || !codeInSession.equals(code)) {
        //3. 比对用户输入的验证码和缓存中的验证码
        if (o == null || !o.equals(code)) {
            //3.1 如果不一致，抛出业务异常
            throw new CustomException("验证码错误");
        }
        //4. 根据手机号判断用户是否存在
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, phone);
        User user = userService.getOne(lqw);
        if (user == null) {
            //4.1 如果不存在？注册（添加到数据库）
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        //5. 判断用户状态
        if (user.getStatus() == 0) {
            //5.1 如果已禁用，不允许，抛出业务异常
            throw new CustomException("用户已禁用");
        }
        //6. 用户登陆成功，存入session
        session.setAttribute("user", user.getId());
        //7. 移除session中的验证码
//        session.removeAttribute(phone);
        //7.移除缓存中的手机号和验证码信息
        redisTemplate.delete(phone);
        return R.success("登陆成功");
    }

    @PostMapping("loginout")
    public R loginout(HttpSession session){

        return R.success("退出成功");
    }
}